import { Injectable, OnModuleInit } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Result } from "src/common/Result";
import { ObjectUtils } from "src/common/utils/ObjectUtils";
import config from "src/config";
import { Unit } from "src/entity/Unit";
import { INIT_CONSTANTS } from "src/InitProjectConstant";
import { Repository } from "typeorm";

@Injectable()
export class UnitService implements OnModuleInit{
    
    
    @InjectRepository(Unit)
    private unitRepository: Repository<Unit>;
    
    /**
     * 初始化单位
     */
    async onModuleInit() {
        if (!config.doInit) {
            return;
        }
        let list: Unit[] = [];
        for (let item of INIT_CONSTANTS.unit.list) {
            let unit = new Unit();
            ObjectUtils.copyProperties(item, unit);
            list.push(unit);
        }
        try {
            await this.unitRepository.save(list);
            console.log("初始化单位成功!")
        } catch (error) {
            console.log("初始化单位失败...")
        }
    }

    /**
     * 单位列表查询
     */
    async selectList(unit: Unit) {
        let queryBuilder = this.unitRepository.createQueryBuilder("u").where("1=1");
        if (unit?.unit) {
            queryBuilder.andWhere(`u.unit = '${unit?.unit}'`);
        }
        return await queryBuilder.getManyAndCount();
    }

    /**
     * 添加单位
     * @param unit 
     */
    async add(unit: Unit) {
        let one = await this.unitRepository.findOneBy({unit: unit.unit});
        if (one) {
            return Result.failed("该单位已存在!");
        }
        await this.unitRepository.save(unit);
        return Result.success();
    }

    /**
     * 编辑单位
     * @param unit 
     */
    async update(unit: Unit) {
        let one = await this.unitRepository.findOneBy({unit: unit.unit});
        if (one && one.unitId != unit.unitId) {
            return Result.failed("该单位已存在!");
        }
        await this.unitRepository.update(unit.unitId, unit);
        return Result.success();
    }
}